package cn.anosi.controller.auth;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.anosi.controller.BaseController;
import cn.anosi.entity.auth.User;
import cn.anosi.page.PageResponseBean;
import cn.anosi.page.Pager;

@Controller
@RequestMapping(value="/user")
public class UserController extends BaseController {
	/**
	 * 用户列表页面
	 * @return
	 */
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(){
		return "auth/user_list";
	}
	
	/**
	 * 用户列表
	 * @param pager
	 * @param name
	 * @return
	 */
	@RequestMapping(value="/list", method=RequestMethod.POST)
	@ResponseBody
	public PageResponseBean<User> users(Pager pager, String name){
		return userService.findAll(pager, name);
	}
	
	/**
	 * 用户添加页面
	 * @return
	 */
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String add(Integer orgId, String orgName, Model model){
		logger.debug("orgId:" + orgId + " orgName:" + orgName);
		model.addAttribute("orgId", orgId);
		model.addAttribute("orgName", orgName);
		return "auth/user_add";
	}
	
	/**
	 * 用户添加
	 * @param user
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/add", method=RequestMethod.POST)
	@ResponseBody
	public User add(User user){
		String salt = RandomStringUtils.random(5);
		user.setSalt(salt);
		String password_md5_sale_1 = new Md5Hash(user.getPassword(), salt, 1).toString();
		user.setPassword(password_md5_sale_1);
		user.setCreateTime(new Date());
		user.setLocked("0");
		return userService.save(user);
	}
	
	/**
	 * 修改用户页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String edit(Integer id, Model model){
		User user = userService.getById(id);
		model.addAttribute("u", user);
		return "auth/user_edit";
	}
	
	/**
	 * 根据id锁定/启用 用户账号
	 * @param id
	 * @param locked
	 * @return
	 */
	@RequestMapping(value="/lock", method=RequestMethod.GET)
	@ResponseBody
	public int lock(Integer id, String locked){
		return userService.lock(id, locked);
	}
	
	/**
	 * 批量锁定用户
	 * @param ids
	 * @return
	 */
	@RequestMapping(value="/batchDel", method=RequestMethod.GET)
	@ResponseBody
	public int batchDel(@RequestBody List<Integer> ids){
		return userService.batchDel(ids);
	}
	
	/**
	 * 根据用户id查询对应的角色id
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/roleIds", method=RequestMethod.POST)
	@ResponseBody
	public List<Integer> roleIds(Integer id){
		List<Integer> ids = userService.roleIds(id);
		return ids;
	}
	
	/**
	 * 用户关联角色
	 * @param ids 
	 * @return
	 */
	@RequestMapping(value="/associateRole", method = RequestMethod.POST)
	@ResponseBody
	public int associateRole(@RequestBody List<Integer> ids){
		if(null != ids && ids.size() > 0){
			Integer userId = ids.get(0);
			ids.remove(0);
			return userService.associateRole(userId, ids);
		}
		return 0;
	}
	
	@RequestMapping(value="/tx/{id}", method=RequestMethod.GET)
	public String tx(@PathVariable Integer id, Model model){
		
		model.addAttribute("id", id);
		return "tx";
	}
	
	/**
	 * 上传头像
	 * @param id
	 * @param img
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/uploadTx", method=RequestMethod.POST)
	@ResponseBody
	public String uploadTx(Integer id,MultipartFile img) throws IOException{
		if(null != img && img != null){
			logger.debug("头像大小:" + img.getSize()/1000 + "k");
			int result = userService.update(id, img.getBytes());
			if(result == 1){
				return "success";
			}else{
				return "fail";
			}
		}
		
		return "fail";
	}
	
	/**
	 * 获取用户头像
	 * @param id
	 * @param response
	 * @param session
	 * @throws IOException
	 */
	@RequestMapping(value="/getTx", method=RequestMethod.GET)
	public void getTx(Integer id, HttpServletResponse response, HttpSession session) throws IOException{
		User user = userService.getById(id);
		byte[] buffer = user.getTx();
		ServletOutputStream out = response.getOutputStream();
		if(buffer != null){
			out.write(buffer);
		}else{
			String realPath = session.getServletContext().getRealPath("img");
			File file = new File(realPath + "/anon.png");
			FileInputStream is = new FileInputStream(file);
			byte[] buf = new byte[is.available()];
			is.read(buf);
			out.write(buf);
			is.close();
		}
		out.close();
	}
}
